package com.example.guessthesoundtrack;

import java.io.IOException;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.view.MotionEvent;

public class Play extends Sprite {
	private MediaPlayer player;
	private Context context;

	public Play(Context context, Bitmap clicked, Bitmap unclicked, float x, float y, float width, float height) {
		super(clicked, unclicked, new Rect((int)x, (int)y, (int)(x + width), (int)(y + height)), x, y, width, height);
		this.context = context;
		
		try {
			AssetFileDescriptor descripter = this.context.getAssets().openFd("daft.punk_get.lucky.mp3");
			player = new MediaPlayer();
			player.setDataSource(descripter.getFileDescriptor(),descripter.getStartOffset(),descripter.getLength());
			player.prepare();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void draw(Canvas canvas) {
		canvas.drawBitmap(getUnclicked(), null, getRect(), null);
	}

	@Override
	public void update(int delta) {
		//int percent = 100 * player.getCurrentPosition() / player.getDuration();
		//Log.d("Guess", "" + percent);
	}

	@Override
	public void onClick(MotionEvent event, float x, float y) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			setDown(true);
			break;
		case MotionEvent.ACTION_MOVE:
			setDown(isColliding(x, y));
			break;
		case MotionEvent.ACTION_UP:
			setDown(false);
			if (!isColliding(x, y))
				return;
			
			if (!player.isPlaying()) {
				try {
					player.start();
				} catch (IllegalStateException e) {
					e.printStackTrace();
				}
			} else {
				player.pause();
			}
			break;
		}
	}

	@Override
	public void onDestroy() {
		player.release();
	}

	@Override
	public boolean isColliding(float x, float y) {
		return (x >= getX() && y >= getY() & x <= getX() + getWidth() && y <= getY() + getHeight());
	}
}